package com.example.controller;

import com.example.common.R;
import com.example.mapper.WorkerMapper;
import com.example.pojo.Worker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author ：伍绍恒
 * @date ：Created in 2022/11/22 14:11
 * @description：
 * @modified By：
 */
@Controller
@ResponseBody
@RequestMapping("/worker")
public class WorkerController {
    @Autowired
    WorkerMapper workerMapper;

    @RequestMapping("/getAll")
    @ResponseBody
    public R<PageInfo> getData(int page, int pageSize, String name) {
        //启用分页
        PageHelper.startPage(page, pageSize, true);
        List<Worker> allWorker = workerMapper.getAllWorkerLikeName(name);
        PageInfo pageInfo = new PageInfo(allWorker);
        return R.success(pageInfo);
    }

    @PostMapping("/login")
    public R<Worker> login(@RequestBody Worker worker, HttpSession session) {
        final Worker loginWorker = workerMapper.getWorkerById(worker.getWId());
        if (loginWorker == null) {//账号出错！
            return R.error("账号错误！请重试");
        }
        if (!loginWorker.getPassword().equals(worker.getPassword())) {
            //密码错误！
            return R.error("密码错误！请重试");
        }
        //保存登录用户的信息到session
        session.setAttribute("worker", loginWorker);
        return R.success(loginWorker);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("worker");
        return R.success("安全退出成功！");
    }

    @DeleteMapping
    public R<String> delete(String wid) {
        int result = workerMapper.deleteWorkerById(wid);
        if (result == 1) {
            return R.success("删除成功！");
        }
        return R.error("删除失败！");
    }

    @GetMapping
    public R<Worker> getWorkerById(String id) {
        final Worker worker = workerMapper.getWorkerById(id);
        return R.success(worker);
    }

    /**
     * @author ：Wushaoheng
     * @date ：2022/11/26 21:26
     * @description：更新员工信息
     * @return类型 ：
     */
    @PutMapping
    public R<String> update(@RequestBody Worker worker) {
        if (workerMapper.updateWorkerById(worker) == 1) {
            return R.success("success");
        }
        return R.error("error");
    }

    /**
     * @author ：Wushaoheng
     * @date ：2022/11/26 23:16
     * @description：添加新员工
     * @return类型 ：
     */
    @PostMapping
    public R<String> add(@RequestBody Worker worker) {
        //新添加员工的密码默认为：123456
        worker.setPassword("123456");
        if (workerMapper.addWorker(worker) == 1) {
            return R.success("添加成功！");
        }
        return R.error("添加失败！");
    }
}
